package com.hong.servicehosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.hong.model.model.hosp.Department;
import com.hong.model.model.hosp.Hospital;
import com.hong.model.vo.hosp.HospitalQueryVo;
import com.hong.model.vo.hosp.HospitalSetQueryVo;
import com.hong.service_cmn_client.feign.DictFeignClient;
import com.hong.servicehosp.repository.HospitalRepository;
import com.hong.servicehosp.service.HospitalService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;
    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    private volatile ExecutorService taskExe;
    private Object lock=new Object();
    private ExecutorService getThreadPoolInstance(){
        if(taskExe==null){
            synchronized (lock){
                if(taskExe==null){
                    taskExe= new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000));
                }
            }
        }
        return taskExe;
    }
    @Override
    public void save(Map<String, Object> paramMap) {
        String string = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(string, Hospital.class);
        //判断是否有相同的数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);
        //如果不存在就进行添加
        if (hospitalExist != null) {
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            //如果存在就进行更新
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hostCode) {
        return hospitalRepository.getHospitalByHoscode(hostCode);
    }

    @Override
    public Page<Hospital> selectHospitalByPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) throws ExecutionException, InterruptedException {
        Pageable pageable = PageRequest.of(page - 1, limit);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnoreCase().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        Example<Hospital> example = Example.of(hospital, exampleMatcher);
        Page<Hospital> all = hospitalRepository.findAll(example, pageable);
        List<Hospital> hospitals = all.getContent();
        for (Hospital hospitalItem : hospitals) {
            setHospitalHosType(hospitalItem);
        }
        return all;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override
    public Map<String, Object> getHospById(String id) throws InterruptedException, ExecutionException {
        Hospital hospital = hospitalRepository.findById(id).get();
        this.setHospitalHosType(hospital);
        Map<String, Object> res = new HashMap<>();
        res.put("hospital", hospital);
        //预约规则
        res.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);
        return res;
    }

    @Override
    public List<Hospital> findByHosName(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> findHospDetail(String hoscode) throws InterruptedException, ExecutionException {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHosType(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode).getHosname();
    }
    private Hospital setHospitalHosType(Hospital hospital) throws InterruptedException, ExecutionException {
        ExecutorService taskExe = getThreadPoolInstance();
        FutureTask getHostypeTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                String hostype = dictFeignClient.getName("Hostype", hospital.getHostype());
                return hostype;
            }
        });
        FutureTask getProvinceTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                String province = dictFeignClient.getName(hospital.getProvinceCode());
                return province;
            }
        });
        FutureTask getCityTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                String city =  dictFeignClient.getName(hospital.getCityCode());
                return city;
            }
        });
        FutureTask getDistrictTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                String district = dictFeignClient.getName(hospital.getDistrictCode());
                return district;
            }
        });
        taskExe.submit(getHostypeTask);
        taskExe.submit(getProvinceTask);
        taskExe.submit(getCityTask);
        taskExe.submit(getDistrictTask);
        //根据dictCode和value获取医院等级名称
        String hostypeString = (String) getHostypeTask.get();
        //查询 省 市 地区  (多线程优化)
        String provinceString = (String) getProvinceTask.get();
        String cityString = (String) getCityTask.get();
        String districtString = (String) getDistrictTask.get();
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", new StringBuilder().append(provinceString).append(cityString).append(districtString).toString());
        return hospital;
    }
}
